namespace Mytodotodaylist.Core.Notifications
{
    using System.Collections.Generic;
    using Entites;
    using Events;
    using History;

    public class NotificationService : INotificationService
    {
        private readonly IHistoryService HistoryService;
        private readonly IEventRepository EventRepository;

        List<IObserver> observers = new List<IObserver>();
        List<Event> allEvents = new List<Event>();
        List<Event> activeEvents = new List<Event>();

        public NotificationService(
            IHistoryService historyService,
            IEventRepository eventRepository)
        {
            HistoryService = historyService;
            EventRepository = eventRepository;

            LoadEvents();
        }

        public void LoadEvents()
        {
            allEvents.Clear();

            var buildSpec = new BuildEventsFromRawSourceSpec();
            allEvents.AddRange(buildSpec.Build());
            
            AknowledgeSubscribersForServiceStateChanges();
        }

        public void NotifyEvents(List<Event> eventsForNotif)
        {
            bool wereAddedNotifs = false;
            
            eventsForNotif.ForEach(x =>
                               {
                                   if (!activeEvents.Contains(x))
                                   {
                                       activeEvents.Add(x);
                                       wereAddedNotifs = true;
                                   }
                               });
            if (wereAddedNotifs)
                AknowledgeSubscribersForServiceStateChanges();
        }

        private void AknowledgeSubscribersForServiceStateChanges()
        {
           observers.ForEach(x => x.Notify());
        }

        public void AttachObserver(IObserver observer)
        {
            if(!observers.Contains(observer))
                observers.Add(observer);
        }

        public List<Notification> ActiveNotifications
        {
            get { return MapAListOfEventsToNotifications(activeEvents); }
        }

        public List<Notification> AllNotifications
        {
            get { return MapAListOfEventsToNotifications(allEvents); }
        }

        private List<Notification> MapAListOfEventsToNotifications(List<Event> events)
        {
            var notifications = new List<Notification>();

            if (events.Count > 0)
                events.ForEach(x => notifications.Add(new Notification(x)));

            return notifications;
        }

        public void MarkAsDone(Notification notification)
        {
            if (allEvents.Contains(notification.TheEvent))
            {
                allEvents.Remove(notification.TheEvent);
                HistoryService.MarkAsDone(notification);
                AknowledgeSubscribersForServiceStateChanges();
            }
        }
    }
}